package com.glodon.paas.task.controller;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.glodon.paas.task.TaskConfig;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


@Controller
public class HomeController {
	public static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView index(){
		return new ModelAndView("index");
	}
	
	@RequestMapping(value="/deleteExpiredFiles", method = RequestMethod.POST)
	@ResponseBody
	public String deleteExpiredFiles(@RequestParam("expiredFiles")String expiredFiles,
			@RequestParam("nDaysBefore")String nDaysBefore,
			@RequestParam("userId")String userId){
		WebResource resource = Client.create().resource(TaskConfig.API_INTERNAL_DOCUMENT_URL+"/cleanExpiredFiles?nDaysBefore="+nDaysBefore+"&expiredFiles="+expiredFiles+"&userId="+userId);
		ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
		int count = Integer.valueOf(c.getEntity(String.class)).intValue();
		System.out.println("deleted "+count+"files");
		return "deleted "+count +" files";
	}
	
	@RequestMapping(value="/createDataBag", method = RequestMethod.POST)
	@ResponseBody
	public String createDataBag(@RequestParam("fileId")String fileId){
		if(StringUtils.isNotBlank(fileId)){
			WebResource resource = Client.create().resource(TaskConfig.API_INTERNAL_DOCUMENT_URL+"/createDataBag?fileId="+fileId);
			ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
			if(c.getStatus() != 204){
				int count = Integer.valueOf(c.getEntity(String.class)).intValue();
				System.out.println("deleted "+count+"files");
			}
			return "finished ";
		}
		else{
			return "File Id should not be empty.";
		}
	}
	
}
